package com.imm.da.main.widget

import android.content.Context
import android.graphics.Canvas
import android.graphics.Color
import android.graphics.Outline
import android.graphics.Paint
import android.graphics.Path
import android.graphics.PorterDuff
import android.graphics.PorterDuffXfermode
import android.graphics.Rect
import android.graphics.RectF
import android.os.Build
import android.util.AttributeSet
import android.view.SurfaceView
import android.view.View
import android.view.ViewOutlineProvider
import com.imm.da.R

/**
 * <p>------------------------------------------------------
 * <p> Copyright (C) 2021 zhangmz, All rights reserved.
 * <p> If there is technical discussion, you can contact zhangmz90@foxmail.com
 * <p>------------------------------------------------------
 * <p> 圆角的SurfaceView，只限5.0以上
 * <p>
 *
 * @author Created by zhangmz
 * @date on 2022/5/12
 */
class RoundSurfaceView @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyle: Int = 0
): SurfaceView(context, attrs, defStyle) {

    private val radius = context.resources.getDimension(R.dimen.dp_100)

    init {
        // 未主动绘制view，需要调用该方法，才会知道draw()，再执行onDraw()
        setWillNotDraw(false)
        clipToOutline = true
    }

    private val rect by lazy(LazyThreadSafetyMode.NONE) {
        val r = Rect().apply { getGlobalVisibleRect(this) }
        RectF(
            0f,
            0f,
            r.width().toFloat(),
            r.height().toFloat())
    }

    private val mPaint by lazy {
        Paint().apply {
            isAntiAlias = true
            color = Color.WHITE
            xfermode = PorterDuffXfermode(PorterDuff.Mode.SRC_IN)
        }
    }

    private val mPath by lazy {
        Path().apply {
            addRoundRect(rect, floatArrayOf(radius, radius, radius, radius, radius, radius, radius, radius), Path.Direction.CW)
        }
    }

    override fun onDraw(canvas: Canvas) {
        super.onDraw(canvas)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            outlineProvider = object : ViewOutlineProvider() {
                override fun getOutline(view: View?, outline: Outline?) {
                    val rect = Rect().apply { view?.getGlobalVisibleRect(this) }
                    outline?.setRoundRect(Rect(0, 0, rect.width(), rect.height()), 100.0f)
                }
            }
        }

    }

}